package com.sky.service.impl;

import com.sky.constant.StatusConstant;
import com.sky.entity.Orders;
import com.sky.mapper.DishMapper;
import com.sky.mapper.OrdersMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.WorkSpaceService;
import com.sky.vo.BusinessDataVO;
import com.sky.vo.DishOverViewVO;
import com.sky.vo.OrderOverViewVO;
import com.sky.vo.SetmealOverViewVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class WorkSpaceServiceImpl implements WorkSpaceService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private SetmealMapper setmealMapper;
    @Autowired
    private DishMapper dishMapper;

    @Override
    public BusinessDataVO getBusinessData(LocalDateTime begin, LocalDateTime end) {
        // - 营业额：已完成订单的总金额
        // 创建map集合
        Map<String, Object> map = new HashMap<>();
        map.put("begin", begin);
        map.put("end", end);
        map.put("status", Orders.COMPLETED);
        // 查询当天时间区间内的营业额数据
        List<Map<String, Object>> countedTurnoverStatistics = ordersMapper.countTurnoverStatistics(map);
        // 转成Double类型 （营业额）
        double turnover = 0.0;
        if (CollectionUtils.isNotEmpty(countedTurnoverStatistics)) {
            if (countedTurnoverStatistics.size() == 1){
                turnover = countedTurnoverStatistics.stream()
                        .findFirst()
                        .map(data -> Double.parseDouble(data.get("totalAmount").toString()))
                        .orElse(0.0);
            }else {
                turnover = countedTurnoverStatistics.stream()
                        .mapToDouble(data -> Double.parseDouble(data.get("totalAmount").toString()))
                        .sum();
            }
        }
        // - 有效订单：已完成订单的数量
        List<Map<String, Object>> validCountOrderStatistics = ordersMapper.countOrderStatistics(map);
        // 获取已完成订单的数量
        Integer validOrderCount = 0;
        if (CollectionUtils.isNotEmpty(validCountOrderStatistics)) {
            if (validCountOrderStatistics.size() == 1){
                validOrderCount = validCountOrderStatistics.stream()
                        .findFirst()
                        .map(data -> Integer.parseInt(data.get("orderCount").toString()))
                        .orElse(0);
            }else {
                validOrderCount = validCountOrderStatistics.stream()
                        .mapToInt(data -> Integer.parseInt(data.get("orderCount").toString()))
                        .sum();
            }
        }
        // - 订单完成率：有效订单数 / 总订单数 * 100%
        // 获取总订单数,创建新map集合
        Map<String, Object> totalOrderOrUserMap = new HashMap<>();
        totalOrderOrUserMap.put("begin", begin);
        totalOrderOrUserMap.put("end", end);
        List<Map<String, Object>> countOrderStatistics = ordersMapper.countOrderStatistics(totalOrderOrUserMap);
        // 获取总订单数
        int totalOrderCount = 0;
        if (CollectionUtils.isNotEmpty(countOrderStatistics)) {
            if (countOrderStatistics.size() == 1){
                totalOrderCount = countOrderStatistics.stream()
                        .findFirst()
                        .map(data -> Integer.parseInt(data.get("orderCount").toString()))
                        .orElse(0);
            }else {
                totalOrderCount = countOrderStatistics.stream()
                        .mapToInt(data -> Integer.parseInt(data.get("orderCount").toString()))
                        .sum();
            }
        }
        // - 平均客单价：营业额 / 有效订单数 (只保留后两位小数)
        double unitPrice = 0.0;
        if (turnover != 0 && validOrderCount != 0) {
            unitPrice = Math.round((turnover / validOrderCount) * 100) / 100.0;
        }
        // - 新增用户：新增用户的数量
        List<Map<String, Object>> countedUserStatistics = userMapper.countUserStatistics(totalOrderOrUserMap);
        int newUsers = 0;
        if (CollectionUtils.isNotEmpty(countedUserStatistics)){
            if (countedUserStatistics.size() == 1){
                newUsers = countedUserStatistics.stream()
                        .findFirst()
                        .map(data -> Integer.parseInt(data.get("totalUser").toString()))
                        .orElse(0);
            }else {
                newUsers = countedUserStatistics.stream()
                        .mapToInt(data -> Integer.parseInt(data.get("totalUser").toString()))
                        .sum();
            }
        }
        // -订单完成率 有效订单数 / 总订单数
        double orderCompletionRate = 0.0;
        if (totalOrderCount != 0 && validOrderCount != 0) {
            orderCompletionRate = validOrderCount.doubleValue() / totalOrderCount;
        }
        return BusinessDataVO.builder()
                .turnover(turnover)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .newUsers(newUsers)
                .unitPrice(unitPrice)
                .build();
    }

    @Override
    public SetmealOverViewVO getSetmealOverview() {
        // 获取已停售套餐数量
        Integer discontinuedSetmealCount = setmealMapper.countSetmealOverview(StatusConstant.DISABLE);
        // 获取已启售套餐数量
        Integer soldSetmealCount = setmealMapper.countSetmealOverview(StatusConstant.ENABLE);
        return SetmealOverViewVO.builder()
                .discontinued(discontinuedSetmealCount)
                .sold(soldSetmealCount)
                .build();
    }

    @Override
    public DishOverViewVO getDishOverview() {
        // 获取已停售菜品数量
        Integer discontinuedDishCount = dishMapper.countDishOverview(StatusConstant.DISABLE);
        // 获取已启售菜品数量
        Integer soldDishCount = dishMapper.countDishOverview(StatusConstant.ENABLE);

        return DishOverViewVO.builder()
                .discontinued(discontinuedDishCount)
                .sold(soldDishCount)
                .build();
    }

    @Override
    public OrderOverViewVO getOrderOverView() {
        // 获取全部订单
        Integer allOrders = ordersMapper.countByStatus(null);
        // 获取已取消数量
        Integer cancelledOrders = ordersMapper.countByStatus(Orders.CANCELLED);
        // 获取已完成数量
        Integer completedOrders = ordersMapper.countByStatus(Orders.COMPLETED);
        // 获取待派送数量
        Integer deliveredOrders = ordersMapper.countByStatus(Orders.CONFIRMED);
        // 获取待接单数量
        Integer waitingOrders = ordersMapper.countByStatus(Orders.TO_BE_CONFIRMED);

        return OrderOverViewVO.builder()
                .allOrders(allOrders)
                .cancelledOrders(cancelledOrders)
                .completedOrders(completedOrders)
                .deliveredOrders(deliveredOrders)
                .waitingOrders(waitingOrders)
                .build();
    }
}
